package org.casper.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 专用于图形验证码的生成工具
 * Servlet implementation class CodeServlet
 */
@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应的类型是图片格式
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache");	//设置禁止缓存
		response.setHeader("Expires", "0");					//设置过期的时间
		
		//在内存中创建图像
		int width = 60;
		int height = 20;
		
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, width, height);
		
		Random random = new Random();
		StringBuffer randCode = new StringBuffer();
		for(int i=0;i<4;i++){
			randCode.append(random.nextInt(10));
		}
		int x=0,y=0;
		
		for(int i=0;i<50;i++){
			x=random.nextInt(width);
			y=random.nextInt(height);
			g.drawOval(x, y, 2, 2);
		}
		/**
		 * 很重要
		 */
		request.getSession().setAttribute("randCode", randCode);
		
		g.setColor(Color.black);
		g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
		g.drawString(randCode.toString(),10, 15);
		g.dispose();
		
		ImageIO.write(image, "jpeg", response.getOutputStream());
	}
	
	
	
	
       
	

}
